package com.avaliacao.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.avaliacao.entity.AbstractEntity;

@SuppressWarnings("unchecked")
public class GenericDAO<T extends AbstractEntity> {

	protected static EntityManager entityManager;

	static {
		EntityManagerFactory fac = Persistence
				.createEntityManagerFactory("avaliacao");
		entityManager = fac.createEntityManager();
	}

	public T getById(Long id) {
		return (T) entityManager.find(getTypeClass(), id);
	}

	public void persist(T entity) {
		try {
			entityManager.getTransaction().begin();
			entityManager.persist(entity);
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			entityManager.getTransaction().rollback();
		}
	}

	public void merge(T entity) {
		try {
			entityManager.getTransaction().begin();
			entityManager.merge(entity);
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			entityManager.getTransaction().rollback();
		}
	}

	public void remove(T entity) {
		try {
			entity = getById(entity.getId());
			entityManager.getTransaction().begin();
			entityManager.remove(entity);
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			entityManager.getTransaction().rollback();
		}
	}

	public List<T> findAll() {
		return entityManager.createQuery(("From " + getTypeClass().getName())).getResultList();
	}

	private Class<?> getTypeClass() {
		Class<?> clazz = (Class<?>) ((ParameterizedType) this.getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
		return clazz;
	}
}